import { storeToRefs } from 'pinia'
import { useMainStore, useSlidesStore } from '@/store'
import { createRandomCode } from '@/utils/common'
import { getImageSize } from '@/utils/image'
import { VIEWPORT_SIZE } from '@/configs/canvas'
import { PPTLineElement, ChartType, PPTElement, TableCell, TableCellStyle, PPTShapeElement } from '@/types/slides'
import { ShapePoolItem } from '@/configs/shapes'
import { LinePoolItem } from '@/configs/lines'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import { getElementListRange } from '@/utils/element'
import { base64ToUrl } from '@/utils/image'

interface CommonElementPosition {
  top: number;
  left: number;
  width: number;
  height: number;
}

interface LineElementPosition {
  top: number;
  left: number;
  start: [number, number];
  end: [number, number];
}

export default () => {
  const mainStore = useMainStore()
  const slidesStore = useSlidesStore()
  const { creatingElement } = storeToRefs(mainStore)
  const { theme, viewportRatio } = storeToRefs(slidesStore)

  const { addHistorySnapshot } = useHistorySnapshot()

  // 创建（插入）一个元素并将其设置为被选中元素
  const createElement = (element: PPTElement) => {

    slidesStore.addElement(element)
    mainStore.setActiveElementIdList([element.id])

    if (creatingElement.value) mainStore.setCreatingElement(null)

    setTimeout(() => {
      mainStore.setEditorareaFocus(true)
    }, 0)

    addHistorySnapshot()
  }

  /**
  * 创建组合元素
  * @param custom 组合元素类型
  */
  const createCustomElement = (position: CommonElementPosition, custom: any) => {
    const { left, top } = position
    const groupId = createRandomCode()
    const { minX, maxX, minY, maxY } = getElementListRange(custom)
    const newArr = JSON.parse(JSON.stringify(custom))
    const arr = newArr.map((item: any) => {
      item.id = createRandomCode()
      item.groupId = groupId
      item.left = item.left - minX + left - (maxX - minX) / 2
      item.top = item.top - minY + top - (maxY - minY) / 2
      return item
    })
    createElement(arr)
  }
  /**
   * 创建图片元素
   * @param src 图片地址
   */
  const createImageElement = (position: CommonElementPosition, src: string, size: any) => {
    const { left, top } = position
    getImageSize(src, size).then(({ width, height }) => {

      const scale = height / width
      if (scale < viewportRatio.value && width > VIEWPORT_SIZE) {
        width = VIEWPORT_SIZE
        height = width * scale
      }
      else if (height > VIEWPORT_SIZE * viewportRatio.value) {
        height = VIEWPORT_SIZE * viewportRatio.value
        width = height / scale
      }
      const obj: any = {
              type: 'image',
              id: createRandomCode(),
              src: src.startsWith('http') ? src + '?id=' + createRandomCode() : src,
              width,
              height,
              left: left ? left - width / 2 : (VIEWPORT_SIZE - width) / 2,
              top: top ? top - height / 2 : (VIEWPORT_SIZE * viewportRatio.value - height) / 2,
              fixedRatio: true,
              rotate: 0,
              hide: false,
              lock: false,
            }
      //如果图片是base64格式则传到华为云
      if (!src.startsWith('http')) {
        createElement(obj)
        // base64ToUrl(src).then(res => {
        //   obj.src = res + '?id=' + createRandomCode()
        //   createElement(obj)
        // }).catch(()=>{
        //   createElement(obj)
        // })
      } else {
        createElement(obj)
      }
      
    })
  }

  /**
   * 创建图表元素
   * @param chartType 图表类型
   */
  const createChartElement = (position: LineElementPosition, chartType: ChartType, antvdata: any) => {
    const { left, top } = position
    console.log(antvdata,'antvdata')
    createElement({
      type: 'chart',
      id: createRandomCode(),
      chartType,
      left: left - 250,
      top: top - 200,
      width: 500,
      height: 400,
      rotate: 0,
      themeColor: [theme.value.themeColor],
      gridColor: theme.value.fontColor,
      data: antvdata,
      hide: false,
      lock: false,
      filters: {},
      attribute: {
        grid: {
          left: 40,
          right: 10,
          top: 50,
          bottom: 20,
        },
        xAxis: {},
        yAxis: {}
      }
    })
  }

  /**
   * 创建表格元素
   * @param row 行数
   * @param col 列数
   */
  const createTableElement = (row: number, col: number) => {
    const style: TableCellStyle = {
      fontname: theme.value.fontName,
      color: theme.value.fontColor,
    }
    const data: TableCell[][] = []
    for (let i = 0; i < row; i++) {
      const rowCells: TableCell[] = []
      for (let j = 0; j < col; j++) {
        rowCells.push({ id: createRandomCode(), colspan: 1, rowspan: 1, text: '', style })
      }
      data.push(rowCells)
    }

    const DEFAULT_CELL_WIDTH = 100
    const DEFAULT_CELL_HEIGHT = 36

    const colWidths: number[] = new Array(col).fill(1 / col)

    const width = col * DEFAULT_CELL_WIDTH
    const height = row * DEFAULT_CELL_HEIGHT

    createElement({
      type: 'table',
      id: createRandomCode(),
      width,
      height,
      colWidths,
      rotate: 0,
      data,
      left: (VIEWPORT_SIZE - width) / 2,
      top: (VIEWPORT_SIZE * viewportRatio.value - height) / 2,
      outline: {
        width: 2,
        style: 'solid',
        color: '#eeece1',
      },
      theme: {
        color: theme.value.themeColor,
        rowHeader: true,
        rowFooter: false,
        colHeader: false,
        colFooter: false,
      },
      hide: false,
      lock: false,
    })
  }

  /**
   * 创建文本元素
   * @param position 位置大小信息
   * @param content 文本内容
   */
  const createTextElement = (position: CommonElementPosition, content: any) => {
    const { left, top, width, height } = position
    createElement({
      type: 'text',
      id: createRandomCode(),
      left: left - content.width / 2,
      top: top - content.height / 2,
      width: content.width,
      height: content.height,
      content: content.content,
      textType: content.name,
      rotate: 0,
      uppcase: false,
      defaultFontName: theme.value.fontName,
      defaultColor: theme.value.fontColor,
      hide: false,
      lock: false,
    })
  }

  /**
   * 创建形状元素
   * @param position 位置大小信息
   * @param data 形状路径信息
   */
  const createShapeElement = (position: CommonElementPosition, data: ShapePoolItem) => {
    const { left, top, width, height } = position
    const newElement: PPTShapeElement = {
      type: 'shape',
      id: createRandomCode(),
      left: left - width / 2,
      top: top - height / 2,
      width,
      height,
      viewBox: data.viewBox,
      path: data.path,
      fill: theme.value.themeColor,
      fixedRatio: false,
      rotate: 0,
      hide: false,
      lock: false,
    }
    if (data.special) newElement.special = true
    createElement(newElement)
  }

  /**
   * 创建线条元素
   * @param position 位置大小信息
   * @param data 线条的路径和样式
   */
  const createLineElement = (position: LineElementPosition, data: LinePoolItem) => {
    const { left, top, start, end } = position

    const newElement: PPTLineElement = {
      type: 'line',
      id: createRandomCode(),
      left: left - 100,
      top: top - 100,
      start,
      end,
      points: data.points,
      color: theme.value.themeColor,
      style: data.style,
      width: 2,
      hide: false,
    }
    if (data.isBroken) newElement.broken = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2]
    if (data.isCurve) newElement.curve = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2]
    createElement(newElement)
  }

  /**
   * 创建LaTeX元素
   * @param svg SVG代码
   */
  const createLatexElement = (data: { path: string; latex: string; w: number; h: number; }) => {
    createElement({
      type: 'latex',
      id: createRandomCode(),
      width: data.w,
      height: data.h,
      rotate: 0,
      left: (VIEWPORT_SIZE - data.w) / 2,
      top: (VIEWPORT_SIZE * viewportRatio.value - data.h) / 2,
      path: data.path,
      latex: data.latex,
      color: theme.value.fontColor,
      strokeWidth: 2,
      viewBox: [data.w, data.h],
      fixedRatio: true,
      hide: false,
    })
  }

  /**
   * 创建视频元素
   * @param src 视频地址
   */
  const createVideoElement = (position: CommonElementPosition, src: string, data = { fileAvatar: ''}) => {
    
    const { left, top } = position
    const obj: any = {
      type: 'video',
      id: createRandomCode(),
      width: 500,
      height: 300,
      rotate: 0,
      left: left ? left - 500 / 2 : (VIEWPORT_SIZE - 500) / 2,
      top: top ? top - 300 / 2 : (VIEWPORT_SIZE * viewportRatio.value - 300) / 2,
      src: src,
      poster: data.fileAvatar,
      hide: false,
    }
    //如果图片是base64格式则传到华为云
    if (!src.startsWith('http')) {
      createElement(obj)
      // base64ToUrl(src).then(res => {
      //   obj.src = res + '?id=' + createRandomCode()
      //   createElement(obj)
      // }).catch(()=>{
      //   createElement(obj)
      // })
    } else {
      createElement(obj)
    }
  }


  /**
   * 创建音频元素
   * @param src 音频地址
   */
  const createAudioElement = (src: string) => {
    const obj: any = {
      type: 'audio',
      id: createRandomCode(),
      width: 50,
      height: 50,
      rotate: 0,
      left: (VIEWPORT_SIZE - 50) / 2,
      top: (VIEWPORT_SIZE * viewportRatio.value - 50) / 2,
      loop: false,
      autoplay: false,
      fixedRatio: true,
      color: theme.value.themeColor,
      src,
      hide: false,
    }
    //如果图片是base64格式则传到华为云
    if (!src.startsWith('http')) {
      createElement(obj)
      // base64ToUrl(src).then(res => {
      //   obj.src = res + '?id=' + createRandomCode()
      //   createElement(obj)
      // }).catch(()=>{
      //   createElement(obj)
      // })
    } else {
      createElement(obj)
    }
  }

  return {
    createImageElement,
    createChartElement,
    createTableElement,
    createTextElement,
    createShapeElement,
    createLineElement,
    createLatexElement,
    createVideoElement,
    createAudioElement,
    createCustomElement,
  }
}